/**
 * LoginController.java
 * Created at 2017-07-06
 * Created by Jackie liu
 * Copyright (C) 2014, All rights reserved.
 */
package com.yunfeisoft.base.controller;

import com.yunfeisoft.base.enumeration.YesNoEnum;
import com.yunfeisoft.base.model.Menu;
import com.yunfeisoft.base.model.Organization;
import com.yunfeisoft.base.model.Role;
import com.yunfeisoft.base.model.User;
import com.yunfeisoft.base.service.inter.MenuService;
import com.yunfeisoft.base.service.inter.OrganizationService;
import com.yunfeisoft.base.service.inter.RoleService;
import com.yunfeisoft.base.service.inter.UserService;
import com.yunfeisoft.common.base.BaseController;
import com.yunfeisoft.common.session.SessionModel;
import com.yunfeisoft.common.session.UserSession;
import com.yunfeisoft.common.utils.*;
import com.yunfeisoft.utils.ApiUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>ClassName: LoginController</p>
 * <p>Description: 用户登录Controller</p>
 * <p>Author: Jackie liu</p>
 * <p>Date: 2017-07-06</p>
 */
@RestController
public class LoginController extends BaseController {

    @Autowired
    private UserService userService;
    @Autowired
    private UserSession userSession;
    @Autowired
    private MenuService menuService;
    @Autowired
    private OrganizationService organizationService;
    @Autowired
    private RoleService roleService;

    /**
     * 用户登录
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/loginIn", method = RequestMethod.POST)
    public Response login(HttpServletRequest request, HttpServletResponse response) {
        Validator validator = new Validator();
        validator.required(request, "account", "账号为空");
        validator.required(request, "pass", "密码为空");
        //validator.required(request, "yzmCode", "验证码为空");
        if (validator.isError()) {
            return ResponseUtils.warn(validator.getMessage());
        }

        /*String verifyCode = userSession.getVerifyCode();
        String yzmCode = ServletRequestUtils.getStringParameter(request, "yzmCode", null).toLowerCase();
        if (!yzmCode.equals(verifyCode)) {
            return ResponseUtils.warn("验证码错误");
        }*/

        String account = ServletRequestUtils.getStringParameter(request, "account", null);
        String pass = ServletRequestUtils.getStringParameter(request, "pass", null);

        List<User> userList = userService.queryByAccount(account);

        if (userList.isEmpty()) {
            return ResponseUtils.warn("该账号不存在");
        }
        if (userList.size() > 1) {
            return ResponseUtils.warn("该账号重复，请联系管理员");
        }

        User user = userList.get(0);
        if (!MD5Utils.validPassword(pass, user.getPass())) {
            return ResponseUtils.warn("密码错误");
        }
        boolean isComplexPass = ValidateUtils.validatePasswordReg2(pass);
        if (!isComplexPass) {
            user.setSimplePass(true);
        }
        getAuthority(user);

        SessionModel sessionModel = new SessionModel();
        sessionModel.setUser(user);
        sessionModel.setToken(KeyUtils.getKey());
        user.setToken(sessionModel.getToken());

        userSession.storageSessionModel(sessionModel);
        request.setAttribute(Constants.SESSION_MODEL, sessionModel);

        return ResponseUtils.success("success", "/view/index");
    }

    /**
     * 获取用户的角色、菜单、组织机构信息
     *
     * @param user 登录用户实例
     */
    private void getAuthority(User user) {
        if (user.getIsSys() == YesNoEnum.YES_ACCPET.getValue()) {
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("state", YesNoEnum.YES_ACCPET.getValue());
            List<Menu> menuList = menuService.query(params);
            user.setMenuList(menuList);
        } else {
            List<Role> roleList = roleService.queryByUserId(user.getId());
            List<Menu> menuList = menuService.queryByUserId(user.getId());

            user.setRoleList(roleList);
            user.setMenuList(menuList);
        }

        Organization organization = organizationService.load(user.getOrgId());
        user.setOrganization(organization);
    }

    /**
     * 用户登出
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/loginOut", method = {RequestMethod.POST, RequestMethod.GET})
    public Response loginOut(HttpServletRequest request, HttpServletResponse response) {
        SessionModel sessionModel = userSession.getSessionModel();

        /*if (userSession instanceof ServletSession && sessionModel != null) {
            ServletSession servletSession = (ServletSession) userSession;
            servletSession.removeKeys(sessionModel.getUser().getId(), sessionModel.getToken());
            log.info("Login out UserSession remove device keys by user id : " + sessionModel.getUser().getId());
        }*/

        userSession.removeSession();
        log.info("Login out UserSession remove session token : " + sessionModel.getToken());
        return ResponseUtils.success("安全退出成功");
    }

    /**
     * 获取登录用户信息
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/web/loginUser", method = {RequestMethod.POST, RequestMethod.GET})
    public Response loginUser(HttpServletRequest request, HttpServletResponse response) {
        User user = ApiUtils.getLoginUser();
        return ResponseUtils.success(user);
    }

    /**
     * 登录验证码
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/yzm", method = {RequestMethod.POST, RequestMethod.GET})
    public void yzm(HttpServletRequest request, HttpServletResponse response) {
        // 设置响应的类型格式为图片格式
        response.setContentType("image/jpeg");
        //禁止图像缓存。
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);


        VerifyCode vCode = new VerifyCode(100, 40, 4, 10);
        userSession.setVerifyCode(vCode.getCode());
        //session.setAttribute("code", vCode.getCode());
        try {
            vCode.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 记录日志
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/log", method = {RequestMethod.POST, RequestMethod.GET})
    public Response log(HttpServletRequest request, HttpServletResponse response) {
        Constants.is_log = true;
        return ResponseUtils.success(Constants.is_log);
    }

    /**
     * 不记录日志
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/unLog", method = {RequestMethod.POST, RequestMethod.GET})
    public Response isLog(HttpServletRequest request, HttpServletResponse response) {
        Constants.is_log = false;
        return ResponseUtils.success(Constants.is_log);
    }
}
